package com.yoke.controller.sysadmin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.UserUtil;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.common.tools.UrlPath;
import com.yoke.service.domain.DoMainServer;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jiangzeyin on 2017/8/7.
 */
@Controller
@RequestMapping("sysadmin")
public class DoMainController extends NginxBaseControl {
    @Resource
    DoMainServer doMainServer;

    @RequestMapping(value = "domain.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String doMain() {
        try {
            List<String> company = doMainServer.getUrls(getBootPath() + "/domain_list.conf", "company");
            List<String> personal = doMainServer.getUrls(getBootPath() + "/domain_list.conf", "personal");
            request.setAttribute("company", company);
            request.setAttribute("personal", personal);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名列表错误", e);
        }
        return "sysadmin/domain";
    }

    @RequestMapping(value = "get_child.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_child(String name) {
        try {
            JSONArray jsonArray = doMainServer.getDomainRList(name);
            if (jsonArray == null)
                return JsonMessage.getString(400, "域名信息错误");
            JSONArray doMain = UrlPath.start(getConfPath(), UrlPath.Type.DoMain);
            if (doMain != null)
                jsonArray.forEach(o -> {
                    JSONObject jsonObject = (JSONObject) o;
                    String urlName = jsonObject.getString("name");
                    if ("@".equals(urlName))
                        return;
                    urlName = String.format("%s.%s", urlName, name);
                    String finalUrlName = urlName;
                    doMain.forEach(o1 -> {
                        JSONObject jsonObject1 = (JSONObject) o1;
                        String url = jsonObject1.getString("url");
                        if (!finalUrlName.equals(url))
                            return;
                        jsonObject.put("need", true);
                    });
                });
            return JsonMessage.getString(200, "", jsonArray);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("域名处理错误", e);
            return JsonMessage.getString(500, "域名信息获取错误，请联系管理员");
        }
    }

    @RequestMapping(value = "domain_conf.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String domain_conf(String prefix, String doMain) {
        return "sysadmin/domain_conf";
    }

    @RequestMapping(value = "save_domain_conf.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_child(String name, String tag, String domain, String prefix) {
        prefix = StringUtil.convertNULL(prefix);
        domain = StringUtil.convertNULL(domain);
        String doMainUrl = String.format("%s.%s", prefix, domain);
        JSONArray jsonArray;
        try {
            jsonArray = doMainServer.getDomainRList(domain);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名异常", e);
            return JsonMessage.getString(500, "处理异常");
        }
        if (jsonArray == null)
            return JsonMessage.getString(400, "域名信息错误");
        Iterator<Object> iterator = jsonArray.iterator();
        boolean find = false;
        while (iterator.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterator.next();
            String urlName = jsonObject.getString("name");
            if ("@".equals(urlName))
                continue;
            urlName = String.format("%s.%s", urlName, domain);
            if (doMainUrl.equals(urlName)) {
                find = true;
                break;
            }
        }
        if (!find)
            return JsonMessage.getString(400, "没有对应域名");
        try {
            JSONArray doMain = UrlPath.start(getConfPath(), UrlPath.Type.DoMain);
            Iterator<Object> iterator1 = doMain.iterator();
            find = false;
            while (iterator1.hasNext()) {
                JSONObject jsonObject1 = (JSONObject) iterator1.next();
                String url = jsonObject1.getString("url");
                if (doMainUrl.equals(url)) {
                    find = true;
                    break;
                }
            }
            if (find) {
                return JsonMessage.getString(400, "该域名异常配置过了");
            }
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名异常", e);
            return JsonMessage.getString(500, "处理异常:-1");
        }
        //
        if (!domain.contains("."))
            return JsonMessage.getString(500, "域名：" + domain + " 错误");
        String pathDomain = domain.substring(0, domain.indexOf("."));
        if (!UserUtil.check(name))
            return JsonMessage.getString(500, "所属人员不正确");
        tag = convertFilePath(tag);
        String rootPath = String.format("/static/ad/%s/%s/%s/", pathDomain, name, tag);
        File rootPathFile = new File(rootPath);
        if (rootPathFile.exists())
            return JsonMessage.getString(500, "对应目录已经存在");
        File nginx_default = new File(getBootPath(), "nginx_default.conf");
        if (!nginx_default.exists())
            return JsonMessage.getString(500, "默认配置错误");
        //
        String default_str;
        try {
            default_str = FileUtil.readToString(nginx_default);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("读取配置异常", e);
            return JsonMessage.getString(500, "读取配置异常");
        }
        // 判断log 文件是否存在
        File logFile = new File(String.format("/var/log/nginx/log/%s/%s.log", pathDomain, prefix));
        if (logFile.exists())
            return JsonMessage.getString(500, "日志文件以及存在");
        File logPath = logFile.getParentFile();// new File(String.format("/var/log/nginx/log/%s/", pathDomain));
        if (!logPath.exists() && !logFile.mkdirs()) {
            //System.out.println("创建成功：" + logPath.getPath());
            return JsonMessage.getString(500, "日志目录创建失败");
        }
        default_str = StringUtil.convertNULL(default_str);
        default_str = default_str.replace("![domain]", doMainUrl);
        default_str = default_str.replace("![root]", rootPath);
        default_str = default_str.replace("![logPath]", pathDomain);
        default_str = default_str.replace("![logName]", prefix);
        File confFile = new File(String.format("%s%s/%s.conf", getConfPath(), name, prefix));
        try {
            FileUtil.writeFile(confFile.getPath(), default_str);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存文件异常", e);
            return JsonMessage.getString(100, "保存文件异常");
        }
        if (new File(rootPathFile, "temp").mkdirs()) {
            return JsonMessage.getString(200, "ok");
        }
        return JsonMessage.getString(100, "目录创建失败");
    }
}
